<template>
  <el-form
    ref="loginFormRef"
    :model="loginForm"
    status-icon
    :rules="rules"
    label-position="top"
  >
    <el-form-item prop="account_name" :label="$t('邮箱')">
      <el-input
        v-model="loginForm.account_name"
        :placeholder="$t('请输入邮箱地址')"
        size="large"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password" :label="$t('密码')">
      <el-input
        type="password"
        v-model="loginForm.password"
        :placeholder="$t('请输入密码')"
        show-password
        @keyup.enter="onLogin"
        size="large"
        class="mt-2"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <!-- <el-form-item prop="captcha_input">
      <div class="flex items-center justify-between flex-1 mt-2">
        <el-input v-model="loginForm.captcha_input" :placeholder="$t('login.captcha')" size="large" style="width: 150px">
        </el-input>

        <div class="w-32 h-10 ml-2 cursor-pointer" @click="handleChangeCaptcha">
          <img :src="captchaSrc" alt="验证码加载中.." class="w-full h-full" ref="captcha" />
        </div>
      </div>
    </el-form-item> -->
  </el-form>
  <el-button
    size="large"
    :plain="true"
    class="w-full mt-2 loginBtn"
    :loading="loading"
    @click="onLogin"
  >
    {{ $t("登录") }}
  </el-button>
  <DialogForm
    @closeDialog="closeDialog"
    :dialogVisible="dialogVisible"
    @callApi="handleLoginGoogleApi"
  />
</template>
<script setup>
import { reactive, ref, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { GetCaptcha, newLogin } from "@/api/login/index";
import { useUserStore } from "@/store/modules/user";
import DialogForm from "../../settings/components/DialogForm.vue";
import { ElMessage } from "element-plus";
import { permissionsUserApi } from "@/api/merchant/index";
const loading = ref(false);
const loginFormRef = ref();
const dialogVisible = ref(false);
const router = useRouter();
const { t } = useI18n();
const useUser = useUserStore();

// let captchaSrc = ref(""); //验证码图片

//获取验证码
// const getCaptcha = async () => {
//   try {
//     const res = await GetCaptcha();
//     captchaSrc.value = `${res.img_url}?${new Date().getTime()}`;
//   } catch (error) { }
// };
// getCaptcha();
// 切换验证码
// const handleChangeCaptcha = async () => {
//   getCaptcha();
// };
//获取验证码

// 打开窗口
const handleClickCreate = () => {
  dialogVisible.value = true;
};
// 关闭窗口
const closeDialog = () => {
  dialogVisible.value = false;
  loading.value = false;
};

// 校验
const rules = computed(() => {
  return {
    account_name: [
      { required: true, message: t("请输入邮箱地址"), trigger: "blur" },
    ],
    password: [{ required: true, message: t("请输入密码"), trigger: "blur" }],
    // captcha_input: [
    //   { required: true, message: t("login.captchaMessage"), trigger: "blur" },
    // ],
  };
});

const loginForm = reactive({
  account_name: "",
  password: "",
  // captcha_input: "",
});
//登录
const onLogin = () => {
  loginFormRef.value
    .validate()
    .then(async () => {
      try {
        loading.value = true;

        // 1.调用登录接口
        const res = await newLogin(loginForm);
        // // // 2.更新用户信息到pinia

        useUser.setUserInfo({
          token: res.token,
          name: loginForm.account_name,
          expire: res.expire,
        });
        //获取权限
        // const permissions = await permissionsUserApi();

        // useUser.setPerm(permissions.perm);

        // if (permissions.is_super == 1) {
        //   useUser.setPermissions(["all"]);
        // } else {
        //   useUser.setPermissions(permissions.permissions);
        // }

        // useUser.setPermissions({ token: res.token, });
        // 3.调整到首页
        router.replace("/");
        ElMessage({
          message: t("欢迎登录"),
          type: "success",
        });
      } catch (error) {
        console.error(error);
        const { data } = error;
        // console.log(data);
        loading.value = false;
        if (data.code == 10259) {
          handleClickCreate();
        }
      }
    })
    .catch((error) => {
      // console.log(error);
    });
};
// 验证码
const handleLoginGoogleApi = async (code) => {
  try {
    // 1.调用登录接口
    const res = await newLogin({ ...loginForm, google_code: code });

    useUser.setUserInfo({ token: res.token, name: loginForm.account_name });
    //获取权限
    const permissions = await permissionsUserApi();

    useUser.setPerm(permissions.perm);

    if (permissions.is_super == 1) {
      useUser.setPermissions(["all"]);
    } else {
      useUser.setPermissions(permissions.permissions);
    }

    ElMessage({
      message: t("欢迎登录"),
      type: "success",
    });
    // 3.调整到首页
    router.replace("/");
  } catch (error) {}
};
</script>
<style scoped></style>
